import { Component, OnInit } from "@angular/core";
import { NzNotificationService, UploadFile } from "ng-zorro-antd";
import { Router, ActivatedRoute } from "@angular/router";
import { HttpServcie} from "../../../service/http.service";
import { Config } from "../../../service/config";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";
import { PlanDetailBean} from "../../supervision/plan/plan-detail.bean";
import { SpotObjectPlan} from "../bean/spotObjectPlan";

@Component({
  selector: "spot-object-detail",
  templateUrl: "spot-object-detail.html",
  styleUrls: ["spot-object-detail.scss"]
})
export class SpotObjectDetail implements OnInit {

  public isSpinning: boolean = false;

  // 定义查询id(行Id)
  public planId:any=[];
  // 定义返回行数据
  public planDict: any = {};
  // 定义实施对象实体类
  public objectPlan:SpotObjectPlan= new SpotObjectPlan();
  // 定义查询多少条数据
  public total = 0;
  // 定义数据
  public list: any = [];
  // 定义模态框表头
  public modelTitle: string;
  // 定义模态框类型
  public modal: number;
  // 定义返回到modify的数据
  public updateList: any = [];
  // 定义检查人员下拉值
  public checkManList:any=[];
  // 定义当前登录人
  public user:any=[];


  updateData: any;
  planDetail: PlanDetailBean = new PlanDetailBean();

  allChecked = false;
  indeterminate = false;
  currentModal: any;
  isConfirmLoading = false;
  isAddVisible = false;
  checkStateList = Config.checkStateList;
  config = Config;

  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {
    this.activatedRoute.params.subscribe(data => {
      //深度 clone 一下，否则不能修改
      this.planDict = Object.assign({}, data);
      this.planId = this.planDict.id;
      this.objectPlan.planId = this.planDict.id;
    });
    this.objectPlan.currentPage = 1;
    this.objectPlan.pageSize = 10;

    //查询
    this.query();



  }

  ngOnInit() {
    this.user = JSON.parse(window.localStorage.getItem("user"));

  }
  // 查询方法
  query() {
    let checkMans:any=[];
    this.httpServcie.findSpotObjectPlans(this.objectPlan).subscribe(data => {
      console.log(data)
      if (data.status == 200) {

        this.list = data.data.list;
        this.total = data.data.total;

        for (let i = 0; i < data.data.list.length; i++) {
          if (checkMans.indexOf(data.data.list[i].checkMan) == -1) {
            checkMans.push(data.data.list[i].checkMan);
          }
        }
        this.checkManList = checkMans;

      } else if (data.status == 401) {
        this._notification.create("error", "失败", "请重新登录");
        this.router.navigateByUrl("/login");
      } else if (data.status == 401) {
        this._notification.create("error", "失败", "请重新登录");
        this.router.navigateByUrl("/login");
      } else {
        this._notification.create("error", "失败", "查询出错！请重试");
      }
    });
  }

  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.objectPlan.pageSize = event;
    this.objectPlan.currentPage = 1;
    this.query();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.objectPlan.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.objectPlan.currentPage = event;
    this.query();
  }

  //下达任务工单
  add(titleTpl, contentTpl, footerTpl) {
    //清空选择项
    this.updateList=[];

    this.modelTitle = "添加";
    this.modal = 0;


    this.list.forEach(element => {
      if (element.checked) {
        this.updateList.push(element);
      }
    });
    if (this.updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请先选择您要下达任务的工单数据！");
      return;
    }
    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  // 实施对象的删除
  delete() {
    const updateList: any = [];
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element.id);
      }
    });
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中您要删除的数据！");
      return;
    }

    let thiss = this;
    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpServcie.deleteObjectPlan({
          ids: updateList.join(",")
        });
        ob.subscribe(
          data => {
            if (data.status == 200) {
              thiss._notification.create("success", "成功", "删除成功");
              thiss.objectPlan.currentPage = 1;
              thiss.query();
            } else if (data.status == 401) {
              thiss._notification.create("error", "失败", "请重新登录");
              thiss.router.navigateByUrl("/login");
            } else {
              thiss._notification.create("error", "失败", "查询出错！请重试");
            }
          },
          error => {
            thiss._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() {}
    });
  }

  // 发送通知
  sendMessage(){
    let userIdList:any=[];

    let parentId =this.user.partyId

    if(parentId == null || parentId == undefined){
      this._notification.create("error", "失败", "请重新登录");
      this.router.navigateByUrl("/login");
      return false;
    }
    for (let i = 0; i < this.list.length; i++) {
      if (this.list[i].checked) {
        if (userIdList.indexOf(this.list[i].userId) == -1) {
          userIdList.push(this.list[i].userId);
        }
      }
    }
    if (userIdList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中您要发送通知的任务工单！");
      return;
    }
    let thiss = this;
    this.modalService.confirm({
      title: "您是否确认要发送这"+userIdList.length +"条任务工单！",
      content: "<b>一旦发送，计划无法删除，用户将收到通知</b>",
      onOk() {
        let ob = thiss.httpServcie.sendMessageObjectPlan({
          parentId: parentId,
          userIdList:userIdList.join(","),
          planId:thiss.planId
        });
        ob.subscribe(
          data => {
            if (data.status == 200) {
              thiss._notification.create("success", "成功", "发送成功");
              thiss.objectPlan.currentPage = 1;
              thiss.query();
            } else if (data.status == 401) {
              thiss._notification.create("error", "失败", "请重新登录");
              thiss.router.navigateByUrl("/login");
            } else {
              thiss._notification.create("error", "失败", "发送出错！请重试");
            }
          },
          error => {
            thiss._notification.create("error", "错误提示", "发送失败！"+error);
          }
        );
      },
      onCancel() {}
    });
  }

  /**
   * 导出维保人员的检查项
   */
  exportExcelObj(data) {
    this.isSpinning=true;

    this.httpServcie.exportExcelObj(data).subscribe(data => {
      if (data.status == 200) {
        this.download(data.data.fileUrl, data.data.fileName);
        this.isSpinning=false;
        this._notification.create("success", "提示", "导出成功");
      } else {
        this._notification.create("error", "提示", "导出失败");
      }
    });
  }

  download(url, name) {
    let link = document.createElement("a");
    let body = document.querySelector("body");

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(
      blob => {
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    );
  }
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

  //添加添加页面的数据
  handleOk(e) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 1000);
    // this.isAddConfirmLoading = true;
    // this.inValue = "aaaaa";
  }

  //关闭model框
  handleCancel = e => {
    console.log(e);
    this.isAddVisible = false;
  };

  //添加后返回的结果
  addOutPut(event) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 500);
    this.objectPlan.currentPage = 1;
    this.query();
  }

  // 返回
  toBack() {
    window.history.back();
  }
}
